// mircoApp/store-oil-station/oilOrder/oilOrder.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    urlStr: "",
    list: [],
    isLoadMore: true,
    page: 1,
    total_page: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options) {
      this.setData({
        active: options.status,
        orderType:options.orderType
      })
    }
    if (options.status == 0) {
      this.data.urlStr = "plugin.store-oil-station.frontend.order-list.index"
    } else if (options.status == 1) {
      this.data.urlStr = "plugin.store-oil-station.frontend.order-list.wait"
    } else {
      this.data.urlStr = "plugin.store-oil-station.frontend.order-list.complete"
    }
    this.setData({
      urlStr: this.data.urlStr
    })
    this.init();
    this.getData();
  },
  init() {
    this.setData({
      page: 1,
      total_page: 0,
      isLoadMore: true
    })
  },
  _toPay(item, btn) {
    if(item.plugin_id == '107'){
      wx.navigateTo({
        url: '/packageD/buy/orderPay/orderPay?order_id=' + item.id + '&status=1'+ '&api=' + btn.api+'&name=bilndBox'
      });
      return;
    }
    if(item.plugin_id == '154'){
      wx.navigateTo({
        url: '/packageD/buy/orderPay/orderPay?order_id=' + item.id + '&status=1'+ '&api=' + btn.api + `&tag=tourAround&ordersn=${item.order_sn}`
      });
      return;
    }
    //status-2合并支付 type-1订单支付
    wx.navigateTo({
      url: "/packageD/buy/orderPay/orderPay?order_id=" + item.id + "&status=1" + "&api=" + btn.api+'&orderType='+this.data.orderType,
    });
  },
  async getData() {
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss(this.data.urlStr),
      data: {
        page: this.data.page
      }
    })
    if (data.result) {
      this.setData({
        list: data.data.data,
        total_page: data.data.last_page,
        isLoadMore: true
      })
    } else {
      app.tips(data.msg)
    }
  },
  //取消订单
  _cancleOrder(item, btn, orderidx) {
    var that = this;
    wx.showModal({
      title: "提示",
      content: "确定取消此订单?",
      success(res) {
        if (res.confirm) {
          //取消当前选中的地址
          // let datasource = that.data.datasource;
          // datasource.splice(orderidx, 1);
          // that.setData({
          //   datasource: datasource,
          // });
          that._sentRequest(btn.api, "&order_id=" + item.id, false);
        }
      },
    });
  },
  _sentRequest(action, params, isIndicator) {
    let urlStr = app.getNetAddresss(action);
    urlStr += params;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500); //延迟时间
            },
          });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  tabChange(e) {
    console.log(e)
    let ind = e.detail.name;
    if (ind == 0) {
      this.data.urlStr = "plugin.store-oil-station.frontend.order-list.index";
    } else if (ind == 1) {
      this.data.urlStr = "plugin.store-oil-station.frontend.order-list.wait";
    } else {
      this.data.urlStr = "plugin.store-oil-station.frontend.order-list.complete";
    }
    this.setData({
      urlStr: this.data.urlStr
    })
    this.init();
    this.getData();
  },
  async getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    }
    this.setData({
      page: this.data.page + 1
    })
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss(this.data.urlStr),
      data: {
        page: this.data.page
      }
    })
    if (data.result) {
      this.setData({
        list: this.data.list.concat(data.data.data)
      })
    } else {
      this.setData({
        page: this.data.page - 1,
        isLoadMore: false
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.isLoadMore){
      this.getMoreData();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //根据按钮值判断用途
  operation(e) {
    let btn = e.currentTarget.dataset.item;
    let order = e.currentTarget.dataset.order;
    let orderidx = e.currentTarget.dataset.orderidx;
    console.log(btn)
    this.setData({
      orderPayId: order.id,
    });
    if (btn.value == "lease_toy_horizon_continue") {
      // 租赁商品续租
      let _url = "/packageD/buy/myOrder_v2/myOrder_v2?tag=rentBuy";
      let goodItem = order.has_many_order_goods[0];
      _url += `&horizon_order_id=${goodItem.order.id}`;
      if (goodItem.goods_id) {
        _url += `&goodsId=${goodItem.goods_id}`;
      }
      if (goodItem.goods_option_id) {
        _url += `&optionsId=${goodItem.goods_option_id}`;
      }
      if (goodItem.total) {
        _url += `&total=${goodItem.total}`;
      }
      wx.navigateTo({
        url: _url,
      })
      console.log(order.has_many_order_goods[0], 'order', _url)
      return
    }
    if (!btn.api && btn.value != 41) {
      if (btn.value == "expediting_delivery") {
        wx.showToast({
          icon: "none",
          title: "已提醒过商家",
          duration: 1000,
        });
      } else {
        //接口没有返回按钮点击请求的地址
        wx.showToast({
          icon: "none",
          title: "缺失必要参数",
          duration: 1000,
        });
      }
      return;
    }

    if (btn.value == 8 || btn.value == "snatch_regiment_express") {
      //查看物流
      this._checklogistics(order, btn);
    } else if (btn.value == 51) {
      //聚合cps
      if (order.plugin_id == "71") {
        wx.navigateTo({
          url: "/packageH/cpsPwd/cpsPwd?id=" + order.id,
        });
      }
    } else if (btn.value == 10) {
      //评价订单
      this._comment(order, btn);
    } else if (btn.value == 1 || btn.value == "snatch_regiment_pay") {
      //订单支付
      this._toPay(order, btn);
    } else if (btn.value == 13 || btn.value == "snatch_regiment_refund" || btn.value == '54') {
      //退款
      this.getTemplate(order, btn);
    } else if (btn.value == 9) {
      //取消订单
      this._cancleOrder(order, btn, orderidx);
    } else if (btn.value == 5) {
      //确认订单
      this._confirmOrder(order, btn);
    } else if (btn.value == 18) {
      //退款中
      this._toRefundDetail(order, btn);
    } else if (btn.value == "cashierPay") {
      //订单已付款
      this._cashPayOrder(order, btn);
    } else if (btn.value == "verification_code") {
      this._verification(order, btn);
    } else if (btn.value == 20) {
      this._verificationCash(order, btn);
    } else if (btn.value == 21) {
      //跳到OrderRecord
      wx.navigateTo({
        url: "/packageD/member/myOrder/order_record/order_record?order_id=" + item.id,
      });
    } else if (btn.value == 22) {
      // 确认支付
      this.publicMessage(btn, order, '支付');
    } else if (btn.value == "coupon") {
      wx.navigateTo({
        url: "/packageD/coupon_share/coupon_share?orderid=" + order.id,
      });
    } else if (btn.value == 23 || btn.value == 60) {
      // 确认发货
      if (order.dispatch_type_id == 3) {
        this.sendGoogs();
      } else {
        this._getCompany();
        this.setData({
          dialogVisible: true,
        });
      }

      this.triggerEvent("stoprefresh", true);
      this.setData({
        expressName: "",
        numberName: "",
      });
    } else if (btn.value == 24 || btn.value == 61) {
      //取消发货
      this.publicMessage(btn, order, '取消发货');
    } else if (btn.value == 25) {
      //确认收货
      this.publicMessage(btn, order, '收货');
    } else if (btn.value == 26) {
      //关闭订单
      this.publicMessage(btn, order, "关闭");
    } else if (btn.value == 30) {
      //退款关闭订单
      this.publicMessage(btn, order, "退款关闭订单");
    } else if (btn.value == 27) {
      this._evaluate(order, btn);
    } else if (btn.value == 28) {
      //卡密
      this._truckList(btn, order);
    } else if (btn.value == 41) {
      //398售后
      this.getKefu(order.has_many_order_goods);
    } else if (btn.value == 50) {
      //查看发票
      this._checkInvoice(btn, order);
    } else if (btn.value == 11) {
      //酒店确认下单
      this.publicMessage(btn, order, "下单");
    } else if (btn.value == "lease_toy_refund") {
      this.publicMessage(btn, order, "申请归还");
    } else if (btn.value == "lease_toy_apply_adopt" || btn.value == 'yz_lease_apply_adopt') {
      if (btn.value == 'yz_lease_apply_adopt') {
        wx.navigateTo({
          url: "/packageB/member/OrderReturn/OrderReturn?id=" + order.id + '&type=yz_lease_apply_adopt',
        });
        return
      }
      wx.navigateTo({
        url: "/packageB/member/OrderReturn/OrderReturn?id=" + order.id,
      });
    } else if (btn.value == "lease_toy_return_info" || btn.value == "yz_lease_return_info") {
      console.log("归还详情");
      if (btn.value == 'yz_lease_return_info') {
        wx.navigateTo({
          url: "/packageA/others/order_ruturn_info/order_ruturn_info?id=" + order.id + '&type=yz_lease_return_info',
        });
        return
      }
      wx.navigateTo({
        url: "/packageA/others/order_ruturn_info/order_ruturn_info?id=" + order.id,
      });
    } else if (btn.value == "yz_lease_refund") {
      // 供应商租赁中台商品 申请归还
      this.publicMessage(btn, order, "申请归还");
    } else if (btn.value == "expediting_delivery") {
      this.publicMessage(btn, order, "提醒商家发货");
    } else if (btn.value == "snatch_regiment_barter") {
      // 抢团易货兑换
      this.setData({
        showBarter: true,
        showBarter_value: order.barter,
      });
    } else if (btn.value == 56) {
      wx.navigateTo({
        url: "/packageH/project_verification/MyProject/MyProject"
      });
    } else if (btn.value == "close_reason") {
      this.setData({
        refundShow: true,
        refundText: order.close_reason
      });
    } else if (btn.value == 140) {
      wx.navigateTo({
        url: "/packageI/brand_resources/cardVoucherInfo/cardVoucherInfo?id=" + order.id
      });
    } else if (btn.value == "city_delivery_detail") {
      wx.navigateTo({
        url: "/packageA/member/order/orderLogisticsDetails/orderLogisticsDetails?id=" + order.id
      });
    } else if (btn.value == "new_blind_box_unpacking") { // 新盲盒商品-去开箱
      wx.navigateTo({
        url: "/packageF/new_blind_box/blindBox/index?order_id=" + order.id
      });
    } else {
      this.publicMessage(btn, order, btn.name);
    }
  },
  publicMessage(btn, order, text) {
    let that = this;
    if (!btn.api) {
      return;
    }
    wx.showModal({
      title: "提示",
      content: `确定${text}?`,
      success(res) {
        if (res.confirm) {
          let urlStr = "";
          urlStr += app.getNetAddresss(btn.api);
          urlStr += "&order_id=" + that.data.orderPayId;
          app._getNetWork({
            url: urlStr,
            success: function (res) {
              var resdata = res.data;
              if (resdata.result == 1) {
                // that.triggerEvent("ConfrimOrderNotification", "pay");
                that.init();
                that.getData();
                if (btn.value == 'inventory_cancel') {
                  wx.showModal({
                    content: '申请成功,请到待发货列表查询此订单',
                  });
                } else if (btn.value == "yz_lease_refund") {
                  app.tips("申请归还成功")
                } else {
                  wx.showToast({
                    icon: "success",
                    title: `${text}成功`,
                    duration: 1000,
                  });
                }
              } else {
                wx.showToast({
                  icon: "none",
                  title: resdata.msg,
                  duration: 1000,
                });
              }
            },
            fail: function (resdata) {
              console.log(resdata);
            },
          });
        }
      },
    });
  },
  // 评价
  _evaluate(order, btn) {
    //抢单评价
    //DeliveryEvaluate
    wx.navigateTo({
      url: "/packageD/member/myOrder/DeliveryEvaluate/DeliveryEvaluate?order_id=" + order.order_id + "&api=" + btn.api + "&name=distributor",
    });
  },
  //获取模板id
  getTemplate(order, btn) {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 2,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray: array,
          });
          wx.requestSubscribeMessage({
            tmplIds: that.data.TemplateArray,
            success(res) {
              that._toRefund(order, btn);
            },
            fail() {
              that._toRefund(order, btn);
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //退款
  _toRefund(item, btn) {
    let _url = '/packageD/member/myOrder/refund/refund';
    // if (item.plugin_id == '107') {
    //   _url = _url + "?order_id=" + item.id + "&type=1" + '&value=' + btn.value
    // } else if (item.plugin_id == '154') {
    //   _url = _url + `?order_id=${item.travel_around_order?.order_id}&type=4&value=${btn.value}&pluginid=${item.plugin_id}`
    // } else {
    _url = _url + "?order_id=" + item.id + "&type=1"
    // }
    wx.navigateTo({
      url: _url
    });
  },
})